/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import dao.LoaiSanPhamDAO;
import dao.SanPhamDAO;
import java.awt.Component;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import pojo.LoaiSanPham;
import pojo.SanPham;

/**
 *
 * @author softviet
 */
public class DanhSachSanPhamGUI extends javax.swing.JPanel {

    /**
     * Creates new form DanhSachSanPham
     */
    private List<SanPham> sanPhams;
    private static Logger logger = Logger.getLogger(DanhSachSanPhamGUI.class);
    
    public DanhSachSanPhamGUI() throws Exception {
        initComponents();
        FormatControl();
        AutoLoad();
    }
    
    private void FormatControl(){
        Utility.FormatNumberStringTextfield(txtMaSanPham);
        Utility.FormatDecimalTextfield(txtDonGiaTo);
        Utility.FormatDecimalTextfield(txtDonGiaFrom);
    }
    
    private void AutoLoad() throws Exception{
        List<LoaiSanPham> loaiSanPhams=(List<LoaiSanPham>) LoaiSanPhamDAO.LayDanhSach(LoaiSanPham.class, MainGUI.nguoiDung);
        Collections.sort(loaiSanPhams, new Comparator<LoaiSanPham>(){

            @Override
            public int compare(LoaiSanPham o1, LoaiSanPham o2) {
                return o1.getTenLoaiSanPham().compareTo(o2.getTenLoaiSanPham());
            }
            
        });
        Utility.SetDataSourceInCombo(loaiSanPhams, cboLoaiSanPham);
        cboLoaiSanPham.setRenderer(new DefaultListCellRenderer(){

            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if(value instanceof LoaiSanPham){
                    LoaiSanPham loaiSanPham=(LoaiSanPham) value;
                    setText(loaiSanPham.getTenLoaiSanPham());
                }
                return this;
            }
            
        });
        cboLoaiSanPham.setSelectedIndex(-1);
        
        sanPhams=(List<SanPham>) SanPhamDAO.LayDanhSach(SanPham.class, MainGUI.nguoiDung);
        Utility.CreateColumnsFromDB(SanPham.class, sanPhams, tbDanhSachSanPham, new String[]{"Mã sản phẩm","Tên sản phẩm","Loại sản phẩm","Đơn giá"}, new String[]{"hinhAnh"});
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtMaSanPham = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtTenSanPham = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cboLoaiSanPham = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        txtDonGiaFrom = new javax.swing.JFormattedTextField();
        jLabel5 = new javax.swing.JLabel();
        txtDonGiaTo = new javax.swing.JFormattedTextField();
        btnTimKiem = new javax.swing.JButton();
        btnThem = new javax.swing.JButton();
        btnSua = new javax.swing.JButton();
        btnXoa = new javax.swing.JButton();
        btnClear = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbDanhSachSanPham = new org.jdesktop.swingx.JXTable();

        jLabel1.setText("Mã sản phẩm");

        jLabel2.setText("Tên sản phẩm");

        jLabel3.setText("Loại sản phẩm");

        jLabel4.setText("Đơn giá từ");

        txtDonGiaFrom.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDonGiaFromFocusLost(evt);
            }
        });

        jLabel5.setText("đến");

        txtDonGiaTo.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDonGiaToFocusLost(evt);
            }
        });

        btnTimKiem.setText("Tìm kiếm");
        btnTimKiem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTimKiemActionPerformed(evt);
            }
        });

        btnThem.setText("Thêm");
        btnThem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThemActionPerformed(evt);
            }
        });

        btnSua.setText("Sửa");
        btnSua.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSuaActionPerformed(evt);
            }
        });

        btnXoa.setText("Xoá");
        btnXoa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnXoaActionPerformed(evt);
            }
        });

        btnClear.setText("Clear");
        btnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnClearActionPerformed(evt);
            }
        });

        tbDanhSachSanPham.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tbDanhSachSanPham.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbDanhSachSanPhamMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbDanhSachSanPham);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(txtTenSanPham, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                            .addComponent(txtMaSanPham))
                        .addGap(71, 71, 71)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(txtDonGiaFrom, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(txtDonGiaTo, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cboLoaiSanPham, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(btnTimKiem)
                        .addGap(18, 18, 18)
                        .addComponent(btnThem)
                        .addGap(18, 18, 18)
                        .addComponent(btnSua)
                        .addGap(18, 18, 18)
                        .addComponent(btnXoa)
                        .addGap(18, 18, 18)
                        .addComponent(btnClear)))
                .addContainerGap(53, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtMaSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(cboLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(txtDonGiaFrom, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(txtDonGiaTo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnTimKiem)
                    .addComponent(btnThem)
                    .addComponent(btnSua)
                    .addComponent(btnXoa)
                    .addComponent(btnClear))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 410, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearActionPerformed
        // TODO add your handling code here:
        Utility.ClearControlInPanel(this);
    }//GEN-LAST:event_btnClearActionPerformed

    private void btnTimKiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimKiemActionPerformed
        try {
            // TODO add your handling code here:
            Integer maSanPham=txtMaSanPham.getText().isEmpty()?null:Integer.parseInt(txtMaSanPham.getText());
            LoaiSanPham loaiSanPham=(LoaiSanPham) cboLoaiSanPham.getModel().getSelectedItem();
            Integer idLoaiSanPham=loaiSanPham!=null?loaiSanPham.getId():null;
            Double donGiaFrom=txtDonGiaFrom.getText().isEmpty()?null:Double.parseDouble(txtDonGiaFrom.getValue().toString());
            Double donGiaTo=txtDonGiaTo.getText().isEmpty()?null:Double.parseDouble(txtDonGiaTo.getValue().toString());
            sanPhams=SanPhamDAO.TimKiem(maSanPham, txtTenSanPham.getText().trim(), idLoaiSanPham, donGiaFrom, donGiaTo);
            Utility.CreateColumnsFromDB(SanPham.class, sanPhams, tbDanhSachSanPham, new String[]{"Mã sản phẩm","Tên sản phẩm","Loại sản phẩm","Đơn giá"}, new String[]{"hinhAnh"});
            if (sanPhams.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Không tìm thấy");
            }
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnTimKiemActionPerformed

    private void txtDonGiaFromFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDonGiaFromFocusLost
        // TODO add your handling code here:
        if(txtDonGiaFrom.getText().isEmpty()){
            txtDonGiaFrom.setValue(null);
        }
    }//GEN-LAST:event_txtDonGiaFromFocusLost

    private void txtDonGiaToFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDonGiaToFocusLost
        // TODO add your handling code here:
        if(txtDonGiaTo.getText().isEmpty()){
            txtDonGiaTo.setValue(null);
        }
    }//GEN-LAST:event_txtDonGiaToFocusLost

    private void btnThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThemActionPerformed
        try {
            // TODO add your handling code here:
            SanPhamGUI sanPhamGUI=new SanPhamGUI(null, true, new SanPham());
            final int x = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getWidth() - sanPhamGUI.getWidth()) / 2;
            final int y = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getHeight() - sanPhamGUI.getHeight()) / 2;
            sanPhamGUI.setLocation(x, y);
            sanPhamGUI.setButtonLuuClickedListener(new MyEventListener() {

                @Override
                public void myEventOccured(Object evt) {
                    SanPham sanPham=(SanPham) evt;
                    if(sanPham!=null){
                        sanPhams.add(sanPham);
                        Utility.CreateColumnsFromDB(SanPham.class, sanPhams, tbDanhSachSanPham, new String[]{"Mã sản phẩm","Tên sản phẩm","Loại sản phẩm","Đơn giá"}, new String[]{"hinhAnh"});
                        tbDanhSachSanPham.changeSelection(tbDanhSachSanPham.getModel().getRowCount()-1, 0, false, false);
                    }
                }
            });
            sanPhamGUI.setVisible(true);
        } catch (Exception ex) {
            logger.error(new Date().toString(), ex);
            JOptionPane.showMessageDialog(this, ex.getMessage());
        }
    }//GEN-LAST:event_btnThemActionPerformed

    private void tbDanhSachSanPhamMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbDanhSachSanPhamMouseClicked
        // TODO add your handling code here:
        if(evt.getClickCount()==2){
            btnSuaActionPerformed(null);
        }
    }//GEN-LAST:event_tbDanhSachSanPhamMouseClicked

    private void btnXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnXoaActionPerformed
        // TODO add your handling code here:
        List<SanPham> sps=(List<SanPham>) Utility.GetSelectedRows(tbDanhSachSanPham, sanPhams);
        if(!sps.isEmpty()){
            if(JOptionPane.showConfirmDialog(this, "Bạn có chắc muốn xoá không?","Question",JOptionPane.YES_NO_OPTION)==0){
                try {
                    for(SanPham sanPham:sps){
                        sanPham.setIsDelete(true);
                    }
                    SanPhamDAO.Xoa(sps);
                    Utility.RemoveSelectedRows(SanPham.class, tbDanhSachSanPham, sanPhams, new String[]{"Mã sản phẩm","Tên sản phẩm","Loại sản phẩm","Đơn giá"}, new String[]{"hinhAnh"});
                    JOptionPane.showMessageDialog(this, "Xoá thành công");
                } catch (Exception ex) {
                    logger.error(new Date().toString(), ex);
                    JOptionPane.showMessageDialog(this, ex.getMessage());
                }
            }
        }
        else{
            JOptionPane.showMessageDialog(this, "Xin chọn dữ liệu trên lưới để xoá");
        }
    }//GEN-LAST:event_btnXoaActionPerformed

    private void btnSuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSuaActionPerformed
        // TODO add your handling code here:
        List<SanPham> sps=(List<SanPham>) Utility.GetSelectedRows(tbDanhSachSanPham, sanPhams);
        if(!sps.isEmpty()){
            try {
                int index=sanPhams.indexOf(sps.get(0));
                SanPhamGUI sanPhamGUI=new SanPhamGUI(null, true, sps.get(0));
                final int x = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getWidth() - sanPhamGUI.getWidth()) / 2;
                final int y = (((JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this)).getHeight() - sanPhamGUI.getHeight()) / 2;
                sanPhamGUI.setLocation(x, y);
                sanPhamGUI.setVisible(true);
                Utility.CreateColumnsFromDB(SanPham.class, sanPhams, tbDanhSachSanPham, new String[]{"Mã sản phẩm","Tên sản phẩm","Loại sản phẩm","Đơn giá"}, new String[]{"hinhAnh"});
                tbDanhSachSanPham.changeSelection(index, 0, false, false);
            } catch (Exception ex) {
                logger.error(new Date().toString(), ex);
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        }
        else{
            JOptionPane.showMessageDialog(this, "Xin chọn dữ liệu trên lưới để sửa");
        }
    }//GEN-LAST:event_btnSuaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnClear;
    private javax.swing.JButton btnSua;
    private javax.swing.JButton btnThem;
    private javax.swing.JButton btnTimKiem;
    private javax.swing.JButton btnXoa;
    private javax.swing.JComboBox cboLoaiSanPham;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private org.jdesktop.swingx.JXTable tbDanhSachSanPham;
    private javax.swing.JFormattedTextField txtDonGiaFrom;
    private javax.swing.JFormattedTextField txtDonGiaTo;
    private javax.swing.JTextField txtMaSanPham;
    private javax.swing.JTextField txtTenSanPham;
    // End of variables declaration//GEN-END:variables
}
